package com.justnow.offer;

import org.omg.CORBA.INTERNAL;
import sun.awt.image.IntegerInterleavedRaster;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author justnow
 * Created on 2020-09-07
 * Description
 */
public class Solution27 {
    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode node6 = new TreeNode(6);
        TreeNode node7 = new TreeNode(7);
        TreeNode node8 = new TreeNode(8);
        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.left = node6;
        node3.right = node7;
        node5.left = node8;

        Solution27 solution26 = new Solution27();
        List<Integer> list = solution26.levelOrder(node1);
        List<Integer> view = solution26.view(node1);
        System.out.println(view);
        System.out.println(list);
    }

    /**
     * 方法一，层次遍历，每次都存放第一个节点
     * @param root
     * @return
     */
    public List<Integer> levelOrder(TreeNode root) {
        List<Integer> list = new LinkedList<>();
        if (root == null)
            return list;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        //层次遍历算法，每次只将该层的第一个节点放入到list中
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (i == 0) {
                    list.add(node.val);
                }
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
        }
        return list;
    }


    /**
     * 方法二，使用前序遍历，根节点 -> 左子节点 -> 右子节点
     * 每次只把每层的第一个左子节点放入到list中。主要是使用一个depth变量来实现这个功能
     */
    public List<Integer> list = new ArrayList<>();
    public List<Integer> view(TreeNode root) {
        preOrder(root, 0);
        return list;
    }

    public void preOrder(TreeNode root, int depth) {
        if (root == null)
            return;
        if (depth == list.size())
            list.add(root.val);
        preOrder(root.left, depth + 1);
        preOrder(root.right, depth + 1);
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    public TreeNode(int x) {
        this.val = x;
    }
}
